using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading;

namespace baiduNLP
{
  public class Sentiment
  {
    private string Url { get; set; }
    private string Token { get; set; }
    public string UrlFormat => Url + Token;

    public Sentiment(string url, string token)
    {
      Url = url;
      Token = token;
    }

    private string GetSentiment(string content)
    {
      string result = null;
      HttpWebRequest req = (HttpWebRequest) WebRequest.Create(UrlFormat);
      req.Method = "POST";
      req.ContentType = "application/json";

      #region 添加Post 参数

      byte[] data = Encoding.UTF8.GetBytes(content);
      req.ContentLength = data.Length;
      using (Stream reqStream = req.GetRequestStream())
      {
        reqStream.Write(data, 0, data.Length);
        reqStream.Close();
      }

      #endregion

      HttpWebResponse resp = (HttpWebResponse) req.GetResponse();
      Stream stream = resp.GetResponseStream();
      //获取响应内容
      using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
      {
        result = reader.ReadToEnd();
        return result;
      }
    }

    public List<sentimentModel> GetSentimentList(List<WordModel> wordDtos)
    {
      List<sentimentModel> sentimentModels = new List<sentimentModel>();
      foreach (WordModel dto in wordDtos)
      {
        var t = GetSentiment(dto.textFormat);
        Thread.Sleep(100);
        Console.WriteLine(t);
        sentimentModels.Add(JsonSerializer.Deserialize<sentimentModel>(t));
      }

      return sentimentModels;
    }
  }
}